import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  // layout主页面组件页面
  {
    path: '/',
    component: () => import('@/views/layout/'),
    // 子路由组件页面
    children: [
      { path: '/', component: () => import('@/views/home/'), meta: { requiresAuth: false } },
      { path: 'home', name: 'home', component: () => import('@/views/home/'), meta: { requiresAuth: false } },
      { path: '/question', name: 'question', component: () => import('@/views/question/'), meta: { requiresAuth: false } },
      { path: '/video', name: 'video', component: () => import('@/views/video/'), meta: { requiresAuth: false } },
      { path: '/my', name: 'my', component: () => import('@/views/my/'), meta: { requiresAuth: false } }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login'),
    meta: { requiresAuth: false }
  },
  {
    path: '/search',
    name: 'search',
    component: () => import('@/views/search'),
    meta: { requiresAuth: false }
  },
  {
    path: '/article/:articleId',
    name: 'article',
    component: () => import('@/views/article'),
    // 将动态路由参数映射到组件的 props 中，无论是访问还是维护性都很方便
    // 参考文档：https://router.vuejs.org/zh/guide/essentials/passing-props.html
    props: true,
    meta: { requiresAuth: false }
  },
  {
    path: '/user/profile',
    name: 'profile',
    component: () => import('@/views/user'),
    meta: { requiresAuth: false }
  },
  {
    path: '/my/homepage/:user_id',
    name: 'homepage',
    component: () => import('@/views/my/components/homepage'),
    meta: { requiresAuth: false },
    props: true
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // 判断页面是否需要登录才能访问
  if (to.meta.requiresAuth) {
    // 如果已登录，则直接通过
    if (store.state.user) {
      return next()
    }
    // 没有登录, 跳转登录页面
    router.replace({
      name: 'login',
      query: {
        redirect: router.currentRoute.fullPath
      }
    })
  } else {
    /// 不需要登录状态的页面，直接过去
    next()
  }
})

export default router
